# -*- coding: utf-8 -*-
import subprocess
import email.mime.text
import email.Header
import email.utils

def mail(toUser, toEmail, subject, message, fromUser = None, fromEmail = None):
    
    toUser = toUser.decode('UTF-8')
    toEmail = toEmail.decode('UTF-8')
    subject = subject.decode('UTF-8')
    message = message.decode('UTF-8')
    if fromUser:
        fromUser = fromUser.decode('UTF-8')
    if fromEmail:
        fromEmail = fromEmail.decode('UTF-8')

    
    charset = 'UTF-8' 
    msg = email.mime.text.MIMEText(message.encode(charset), _charset=charset, _subtype='html')
    msg['Subject'] = email.Header.Header(subject, charset)

    if fromEmail:
        if fromUser:
            msg['From'] = "%s <%s>" % (email.Header.Header(fromUser, charset), fromEmail)
        else:
            msg['From'] = fromEmail
    else:
        msg['From'] = "%s <%s>" % ('taketrip.ru', 'noreply@taketrip.ru')

    if toUser:
        msg['To'] = "%s <%s>" % (email.Header.Header(toUser, charset), toEmail)
    else:
        msg['To'] = toEmail
    msg['Date'] = email.utils.formatdate()


    
    p = subprocess.Popen(['/usr/sbin/sendmail', '-i', '-t'], shell=False, stdin=subprocess.PIPE)
    p.stdin.write( msg.as_string() )
    p.stdin.close()
    
    return True